<?php

class Common
{
    private static   $vip1 = 1 ;//一级代理商
    private static   $vip2 = 2 ;//二级代理商
    private static   $vip3 = 3 ;//县代理
    private static   $vip4 = 4 ;//市代理

    //因为项目需求改动 这里的grade_id 可能是vip_id  vip_id是实际等级 grade_id为虚升  默认vip_id = grade_id

    /**
     * @param $grade_id 等级id 对应grade表中的id字段
     * @return mixed
     */
    public static function getInvestInfoByGradeId($grade_id)
    {
        $model = new Model();
        $investInformation = $model ->table("grade")->where("id =".intval($grade_id))->find();//获取级别id对应的等级信息
        return $investInformation;
    }

    public static function getLimitZcByUserId($id)
    {
        $model = new Model();
        $investInformation = $model ->table("customer")->where("user_id =".$id)->find();//获取级别id对应的等级信息
        return self::getZcByGradeId($investInformation['vip_id']) ;
    }

    /**
     * @param $id 会员级别
     * @return mixed 在配置 中 返回投资级别对应的资产仓值
     */
    public static function getZcByGradeId($grade_id)
    {
        $investInformation = self::getInvestInfoByGradeId($grade_id);  //会员的等级 grade表中的信息

        if(intval($investInformation['id'] ) === intval(self::$vip1))
        {
            $zc = $investInformation['money'] * self::getConfigJjSetValue('jjset_grade_times1');
        }
        elseif(intval($investInformation['id'] ) === intval(self::$vip2))
        {
            $zc = $investInformation['money'] * self::getConfigJjSetValue('jjset_grade_times2');
        }
        elseif(intval($investInformation['id'] ) === intval(self::$vip3))
        {
            $zc = $investInformation['money'] * self::getConfigJjSetValue('jjset_grade_times3');
        }
        elseif(intval($investInformation['id'] ) === intval(self::$vip4))
        {
            $zc = $investInformation['money'] * self::getConfigJjSetValue('jjset_grade_times4');
        }
        return $zc;
    }


    /**
     * @param $id 用户的id
     * @return mixed 根据用户的id 找到他每天分红的积分
     */
    public static function getDayFhByUserId($id)
    {
        $model = new Model();
        $customer =  $model ->table("customer")->where("user_id =".$id)->find();
        return self::getDayFhByGradeId($customer["vip_id"]);

    }


    /**
     * @param $grade_id  //投资会员的级别id
     * @return mixed  //根据投资级别获取对应 每天分红盈利积分
     */
    public static function getDayFhByGradeId($grade_id)
    {
        if(intval($grade_id) === intval(self::$vip1) )       //一级代理商的每天分红积分
        {
            $DayFh =self::getConfigJjSetValue('jjset_fhj1');
        }
        elseif(intval($grade_id) === intval(self::$vip2) )
        {
            $DayFh =self::getConfigJjSetValue('jjset_fhj2');
        }
        elseif(intval($grade_id) === intval(self::$vip3) )
        {
            $DayFh =self::getConfigJjSetValue('jjset_fhj3');
        }
        elseif(intval($grade_id) === intval(self::$vip4) )
        {
            $DayFh =self::getConfigJjSetValue('jjset_fhj4');
        }

        return $DayFh;
    }

    /**
     * @param $grade_id  //会员等级
     * @return mixed 根据会员等级 获取对应的投资金额
     */
    public static function getInvestMoneyByGradeId($grade_id)
    {
        $investInformation = self::getInvestInfoByGradeId($grade_id);  //会员的等级 grade表中的信息
        return $investInformation["money"];

    }


    /**
     * 获取投资金额  通过用户的id
     * @param $id
     */
    public static function getInvestMoneyByUserId($id)
    {
        $model = new Model();
        $customer =  $model ->table("customer")->where("user_id =".$id)->find(); //获取用户信息

        return self::getInvestMoneyByGradeId($customer['vip_id']);

    }

    /**
     * @param $id 用户的id
     * @param $dai 查询几代
     * @return array  返回上几代用户数组
     */
    public static function getTjrListByUserId($id, $dai)
    {
        $TjrList_array  = array();
        $userObj = self::getUserInfoById($id);         //获取当前用户信息;

        $i = 0;
        while( intval($userObj['tjr_id']) !== 0 && $i <$dai  ){
            $TjrList_array[] = self::getUserInfoById($userObj['tjr_id']);

            $userObj = self::getUserInfoById($userObj['tjr_id']);
            $i++;
        }
        return $TjrList_array;
    }



    /**
     * @param $id 用户的id
     * @return mixed 返回用户的信息
     */
    public static function getUserInfoById($id)
    {
        $model = new Model();
        $user = $model ->table("user")->where("id =".$id)->find(); //获取信息
        return $user;
    }

    /**
     * @param $id
     * @return mixed 返回用户的推荐人数
     */
    public static function getUserValidTjrsById($id)
    {
        $model = new Model();
        $tjrs = $model ->table("user as u")->join("inner join customer as c on u.id =c.user_id ")->where("c.zc>0 and c.last_fhjf>0 and u.status =1 and tjr_id = $id ")->count(); //获取信息
        return $tjrs ;
    }
    /**
     * @param $id 用户的id
     * @return mixed 返回用户的信息
     */
    public static function getCustomerInfoById($id)
    {
        $model = new Model();
        $user = $model ->table("customer")->where("user_id =".$id)->find(); //获取信息
        return $user;
    }
    /**
     * @param $id 用户的id
     * @return mixed 返回用户的信息
     */
    public static function UpdatezcByCustomer($CustomerObj)
    {
        $model = new Model();
        $user = $model ->table("customer")->where("user_id =".$CustomerObj["user_id"])->data(array("zc" =>"0"))->update();
        return $user;
    }
    /**
     * @param $key
     * @return mixed 配置文件中的奖金类型数据
     */
    public static function getConfig($key)
    {
        $config = Config::getInstance();
        return $config->get("jjset")[$key];
    }

    /**
     * @param $id
     * @return float 得到一个用户的所有奖金
     */
    static function get_jj_all_jjmix($id)
    {
        $model = new Model();
        $fhj = $model ->query("select sum(fhj)as total_fhj,sum(kzj) as total_kzj,sum(zlj) as total_zlj from zyk_jjmx where user_id = $id");
        return floatval($fhj[0]['total_fhj'])+floatval($fhj[0]['total_kzj'])+floatval($fhj[0]['total_zlj']);

    }


    static function get_user_gq_zje($user_id)
    {
        $model = new Model();
        $result = $model->query("select sum(zh_money) as total_je from zyk_zh where user_id=$user_id and (zh_lx=0 or zh_lx=1)");
        return floatval($result[0]['total_je']);
    }

    //$status === 2 || $status===3) && $pay_status===1 && $delivery_status===0
    /**
     * 检测父代是否购物
     * @param unknown $user_id
     */
    public static function check_tjr_is_wan($user_id)
    {
        //$tjr_list = self::get_dai_tjr_list($user_id, 1);
        $model = new Model();
        //$flag = true;
        $user_obj = self::get_user_obj($user_id);
        $tjr_id = $user_obj['tjr_id'];
        //$count1 = $model->table("order")->where("user_id=$user_id and (status=2 or status=3) and pay_status=1 and delivery_status=0")->count();
        //$count2 = $model->table("order")->where("user_id=$tjr_id and (status=2 or status=3) and pay_status=1 and delivery_status=0")->count();
        $count1 = $model->table("zh")->where("user_id=$user_id and (zh_lx=0 or zh_lx=1)")->count();
        $count2 = $model->table("zh")->where("user_id=$tjr_id and (zh_lx=0 or zh_lx=1)")->count();
        if ($count1 <= 0 && $count2 <= 0) {
            return false;
        }
        return true;
        /*
        $count = 0;
        for($i=0,$c=count($tjr_list); $i<$c; $i++)
        {
            $tjr_id = $tjr_list[$i]['id'];
            $count = $model->table("order")->where("user_id=$tjr_id and (status=2 or status=3) and pay_status=1 and delivery_status=0")->count();
            if($count <= 0)
            {
                $flag =false;
            }
        }
        */
        //return $flag;
    }

    public static function jisuan_tuan_yj($user_id)
    {
        $model = new Model();
        $obj = self::get_user_obj($user_id);
        $arr = explode(",", $obj['son']);
        if (count($arr) > 0) {
            $total_je = 0;
            foreach ($arr as $v) {
                $result = $model->query("select sum(zh_money) as total_je from zyk_zh where user_id=$v and (zh_lx=0 or zh_lx=1)");
                $total_je += $result[0]['total_je'];
            }
            if ($total_je > 0) {
                $model->table("user")->data(['tuan_yj' => $total_je])->where("id=$user_id")->update();
            }
        }
    }

    public static function download_recharge_execl_file()
    {
        date_default_timezone_set('Asia/Shanghai');
        require_once 'PHPExcelClasses/PHPExcel.php';
        require_once 'PHPExcelClasses/PHPExcel/IOFactory.php';
        require_once 'PHPExcelClasses/PHPExcel/Reader/Excel5.php';
        $model = new Model();
        //$data  = $model->table("user")->fields("name,real_name,pass1,pass2,ok_gwqqb,reg_time,mobile,head_pic,status,nojj,jh_time")->order("id desc")->select();
        $data = $model->query("select u.name as uname,u.number,c.real_name,w.* from zyk_user as u,zyk_recharge as w,zyk_customer as c where u.id=w.user_id and u.id=c.user_id order by w.id desc");
        header("content-type:text/html;charset=utf-8");

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator('http://www.jb51.net')
            ->setLastModifiedBy('http://www.jb51.net')
            ->setTitle('Office 2007 XLSX Document')
            ->setSubject('Office 2007 XLSX Document')
            ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Result file');

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '会员编码')
            ->setCellValue('C1', '账号')
            ->setCellValue('D1', '姓名')
            ->setCellValue('E1', '充值金额')
            ->setCellValue('F1', '操作类型')
            ->setCellValue('G1', '账户类型')
            ->setCellValue('H1', '充值时间')
            ->setCellValue('I1', '操作人');

        $i = 2;
        foreach ($data as $k => $v) {
            if ($v['type'] == 0) {
                $type = '充值';
            } else {
                $type = '扣款';
            }

            $account_type = Common::get_account_name($v['account_type']);

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $i, ($i - 1) . " ")
                ->setCellValue('B' . $i, $v['number'] . " ")
                ->setCellValue('C' . $i, $v['uname'] . " ")
                ->setCellValue('D' . $i, $v['real_name'] . " ")
                ->setCellValue('E' . $i, $v['je'] . " ")
                ->setCellValue('F' . $i, $type)
                ->setCellValue('G' . $i, $account_type . " ")
                ->setCellValue('H' . $i, $v['create_time'] . " ")
                ->setCellValue('I' . $i, $v['admin']);
            /*
             ->setCellValue('E'.$i,$v['sfje'])
             ->setCellValue('F'.$i,$v['hl'])
             ->setCellValue('G'.$i,$v['sf_rmb'])
             ->setCellValue('H'.$i,$v['real_name'])
             ->setCellValue('I'.$i,$v['bank'])
             ->setCellValue('J'.$i,$v['bankkh']." ")
             ->setCellValue('K'.$i,$v['mobile'])
             ->setCellValue('L'.$i,$v['time'])
             ->setCellValue('M'.$i,$v['st']);
            */
            $i++;
        }
        $objPHPExcel->getActiveSheet()->setTitle('列表1');
        $objPHPExcel->setActiveSheetIndex(0);
        //$filename=urlencode('学生信息统计表').'_'.date('Y-m-dHis');
        $filename = '用户充值扣款记录' . '_' . date('Y-m-d');


        //生成xls文件
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $objWriter->save('php://output');
        exit;
    }

    /**
     * 导出提现excel记录记录
     */
    public static function download_widthdraw_execl_file()
    {
        date_default_timezone_set('Asia/Shanghai');
        require_once 'PHPExcelClasses/PHPExcel.php';
        require_once 'PHPExcelClasses/PHPExcel/IOFactory.php';
        require_once 'PHPExcelClasses/PHPExcel/Reader/Excel5.php';
        $model = new Model();
        //$data  = $model->table("user")->fields("name,real_name,pass1,pass2,ok_gwqqb,reg_time,mobile,head_pic,status,nojj,jh_time")->order("id desc")->select();
        $data = $model->query("select u.name as uname,u.number,w.* from zyk_user as u,zyk_withdraw as w where u.id=w.user_id order by w.status asc");

        header("content-type:text/html;charset=utf-8");

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator('http://www.jb51.net')
            ->setLastModifiedBy('http://www.jb51.net')
            ->setTitle('Office 2007 XLSX Document')
            ->setSubject('Office 2007 XLSX Document')
            ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Result file');

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '推荐编码')
            ->setCellValue('C1', '用户名')
            ->setCellValue('D1', '申请金额')
            ->setCellValue('E1', '手续费')
            ->setCellValue('F1', '实发金额')
            ->setCellValue('G1', '真实姓名')
            ->setCellValue('H1', '金融机构')
            ->setCellValue('I1', '金融账号')
            ->setCellValue('J1', '申请时间')
            ->setCellValue('K1', '状态');

        $i = 2;
        foreach ($data as $k => $v) {
            $str = '';
            if ($v['status'] == 0) {
                $str = '等待处理';
            } elseif ($v['status'] == 1) {
                $str = '同意';
            } elseif ($v['status'] == 2) {
                $str = '拒绝';
            }

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $i, $k + 1)
                ->setCellValue('B' . $i, $v['number'] . " ")
                ->setCellValue('C' . $i, $v['uname'] . " ")
                ->setCellValue('D' . $i, $v['sq_money'])
                ->setCellValue('E' . $i, $v['txf'])
                ->setCellValue('F' . $i, $v['amount'])
                ->setCellValue('G' . $i, $v['name'])
                ->setCellValue('H' . $i, $v['type_name'])
                //设置输出文本为字符串
                ->setCellValueExplicit("I" . $i, $v['account'], PHPExcel_Cell_DataType::TYPE_STRING)
                // ->setCellValue('I'.$i,strval($v['account'])." ")
                ->setCellValue('J' . $i, $v['time'] . " ")
                ->setCellValue('K' . $i, $str);
            /*
             ->setCellValue('E'.$i,$v['sfje'])
             ->setCellValue('F'.$i,$v['hl'])
             ->setCellValue('G'.$i,$v['sf_rmb'])
             ->setCellValue('H'.$i,$v['real_name'])
             ->setCellValue('I'.$i,$v['bank'])
             ->setCellValue('J'.$i,$v['bankkh']." ")
             ->setCellValue('K'.$i,$v['mobile'])
             ->setCellValue('L'.$i,$v['time'])
             ->setCellValue('M'.$i,$v['st']);
            */
            $i++;
        }

        $objPHPExcel->getActiveSheet()->setTitle('列表1');
        $objPHPExcel->setActiveSheetIndex(0);
        //$filename=urlencode('学生信息统计表').'_'.date('Y-m-dHis');
        $filename = '用户记录' . '_' . date('Y-m-d');


        //生成xls文件
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $objWriter->save('php://output');
        exit;
    }


    static function get_goods_sell_name($category_id)
    {

        $model = new Model();
        $category_obj = self::get_category_obj($category_id);
        $arr = explode(',', $category_obj['path']);
        $cid = intval($arr[1]);
        if ($cid === 63) {
            return '购物积分';
        } elseif ($cid === 64) {
            return '重消积分';
        }

    }

    static function is_not_allow_do_by_time()
    {
        $now_h = intval(date("H"));
        $now_i = intval(date("i"));
        if ($now_h >= 23 && $now_i >= 40) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 得到完整的路径
     * @param string $arg
     * @return string
     */
    static function get_complete_path($arg = '')
    {
        $tjr_href = Url::getEntryUrl() . Url::createUrl($arg);
        return $tjr_href;
    }

    /**
     * 删除某个指定的文件
     */
    static function del_file($filepath)
    {
        if (is_file($filepath)) {
            unlink($filepath);
        }
    }

    //品牌商城类别id
    //static $xfq_category_id = 63;

    //积分上海层类别id
    //static $point_category_id = 64;

    /**
     * 根据分类id得到分类对象
     * @param unknown $id
     */
    static function get_category_obj($id)
    {
        $model = new Model();
        return $model->table("goods_category")->where("id=$id")->find();
    }


    /**
     * 根据商品1级分类类别得到商品2级分类列表
     * @param unknown $first_level_category
     */
    /*
    static function get_goods_second_level_category_list($category_type)
    {
        $model = new Model();
        if($category_type == 'voucher')
        {
            $where_str = "parent_id=".self::$xfq_category_id;
        }
        elseif($category_type == 'ok_xfjf')
        {
            $where_str = "parent_id=".self::$point_category_id;
        }
        $list = $model->table("goods_category")->where("parent_id=".self::$xfq_category_id)->select();
        return $list;
    }
    */

    /**
     * 根据第2级类别id得到商品第3级分类列表
     * @param unknown $category_id
     */
    /*
    static function get_goods_third_level_category_list($category_id)
    {
        $model = new Model();
        $list = $model->table("goods_category")->where("parent_id=".$category_id)->select();
        return $list;
    }
    */


    static function get_payment_obj_by_id($id)
    {
        $model = new Model();
        return $model->table("payment")->where("id=$id")->find();
    }

    static function get_order_obj_by_id($order_id)
    {
        $model = new Model();
        return $model->table("order")->where("id=$order_id")->find();
    }

    /**
     * 检测将要提交的多个商品列表中是否属于同一个分类（大类）
     */
    static function check_goods_list_is_one_category($order_products)
    {
        $model = new Model();
        sort($order_products);
        $arr = [];
        foreach ($order_products as $key => $value) {
            //商品id
            $goods_id = $value['goods_id'];
            $goodsObj = $model->table("goods")->fields("category_id")->where("id=" . $goods_id)->find();
            //商品分类id
            $category_id = $goodsObj['category_id'];
            $category_obj = self::get_category_obj($category_id);
            $path_arr = explode(",", $category_obj['path']);
            $cid = $path_arr[1];
            $arr[$cid] = 0;
        }
        if (count($arr) > 1 || count($arr) < 1) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 得到订单的支付方式
     */
    static function get_order_payment_id($order_products)
    {
        $model = new Model();
        sort($order_products);
        $arr = [];
        foreach ($order_products as $key => $value) {
            //商品id
            $goods_id = $value['goods_id'];
            $goodsObj = $model->table("goods")->fields("category_id")->where("id=" . $goods_id)->find();
            //商品分类id
            $category_id = $goodsObj['category_id'];
            $category_obj = self::get_category_obj($category_id);
            $path_arr = explode(",", $category_obj['path']);
            $cid = intval($path_arr[1]);
            if ($cid === 63) {
                return 10;
            } else {
                return 11;
            }
        }

    }


    /*
    static function get_category_obj($category_id)
    {
        $model = new Model();
        return $model->table("goods_category")->where("id=$category_id")->find();
    }
    */
    /**
     * 检测用户是否被冻结
     *
     * @param int $user_id
     * @return true or false
     */
    static function check_user_is_freeze($user_id)
    {
        $model = new Model();
        $result = $model->table("user")->fields("nojj")->where("id=$user_id")->find();
        if (intval($result['nojj']) === 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户id得到团队人数
     * Enter description here ...
     */
    public static function getUserTuanNums($user_id)
    {
        $model = new Model();
        $obj = self::get_user_obj($user_id);
        $son = $obj['son'];
        if (empty($son)) {
            return 0;
        } else {
            $arr = explode(",", $son);
            return count($arr);
        }
    }


    //在Common类中顶一个静态变量
    private static $drr = null;

    /**
     * 得到3代推荐人列表
     *
     * @param unknown_type $tjr_id
     * @param unknown_type $from
     */
    public static function get_dai_tjr_list($user_id, $dai)//得到该用户的上3代推荐让人
    {
        self::$drr = null;//调用该方法前，先初始化静态变量为null

        $obj = self::get_user_obj($user_id);//根据usera_id得到用户对象
        if (intval($obj['tjr_id']) === 0)//如果该用户的推荐人id不存在
        {
            return null;//返回null
        } else {
            return self::get_dai($obj['tjr_id'], $dai);
        }

    }

    public static function get_dai($tjr_id, $dai)
    {
        static $count = 0;//该变量用于终止递归的执行
        $count++;
        //根据推荐人id查出推荐人对象
        $tuiObj = self::get_user_obj($tjr_id);
        //如果推荐人对象不为空
        if (!empty($tuiObj)) {
            self::$drr[] = $tuiObj;
        }


        if ($count < $dai && intval($tuiObj['tjr_id']) !== 0) {
            return self::get_dai($tuiObj['tjr_id'], $dai); //这一步很重要 谨慎小心 return很重要
        } else {
            $count = 0;
            return self::$drr;
        }

    }


    /**
     * 购物后自动升级用户为合格会员
     */
    static function auto_sj_user_to_hg($user_id)
    {
        $model = new Model();
        $xfq_1 = Common::getConfigJjsetValue("jjset_xfq_1");
        $xfq_2 = Common::getConfigJjsetValue("jjset_xfq_2");
        //查询消费券购物消耗的总额度
        $res = $model->query("select sum(xzyj) as total_je from zyk_every_day_xzyj where user_id=$user_id and xf_type=1");
        $total_je = $res[0]['total_je'];
        if ($total_je >= $xfq_1 && $total_je <= $xfq_2) {
            $model->query("update zyk_user set is_hg=1 where id=$user_id");
        }
    }


    /**
     * 每次购物后 或者 购买积分后 都要保存该记录
     * 保存会员每日新增业绩记录
     * @param unknown $user_id
     * @param unknown $xzyj
     * @param unknown $status
     * @param unknown $no
     * @param int xf_type 0购买积分  1消费券购物（可返还各种积分） 2可用积分购物
     */
    static function save_every_day_xzyj($user_id, $xzyj, $status, $no, $xf_type)
    {
        $model = new Model();
        $data['user_id'] = $user_id;
        //新增业绩
        $data['xzyj'] = $xzyj;
        $data['status'] = $status;//0购物  1购买积分 2兑换
        //购物时，保存订单编号   买积分时buy表的id
        $data['no'] = $no;
        $data['xf_type'] = $xf_type;
        $data['create_time'] = date('Y-m-d H:i:s');
        //奖扣除的反哺费保存到新增业绩表中
        $res = $model->table("every_day_xzyj")->data($data)->insert();
        return $res;
    }


    /**
     * 验证二级密码
     * @param unknown $user_id
     * @param unknown $pass2
     */
    static function check_pass2($user_id, $pass2)
    {
        $user_obj = self::get_user_obj($user_id);
        return (strval($user_obj['passwordtwo']) === strval(md5($pass2)));
    }

    static function return_info_msg($status, $msg)
    {
        $info = ['status' => $status, 'msg' => $msg];
        echo JSON::encode($info);
    }

    /** 账户类型对应的字段
     * @param $account_type
     * @return string
     */
    static function get_account_zd($account_type)
    {
        if($account_type === 1)
        {
            $demo_account_type = 'zcf';
        }
        elseif($account_type === 2)
        {
            $demo_account_type = "jjf";
        }
        elseif($account_type === 3)
        {
            $demo_account_type = "xjf";
        }
        elseif($account_type === 4)
        {
            $demo_account_type = "gwjf";
        }
        elseif($account_type === 5)
        {
            $demo_account_type = "cxjf";
        }
        elseif($account_type === 6)
        {
            $demo_account_type = "zc";
        }
        elseif($account_type === 7)
        {
            $demo_account_type = "last_fhjf";
        }
        return $demo_account_type;
    }

    /** 账户类型的名字
     * @param $index
     * @return mixed
     */
    static function get_account_name($index)
    {
        $arr = ['', '注册分', '奖金分', '现金分', '购物积分', '重消积分','资产','剩余分红积分'];
        return $arr[$index];
    }

    //根据用户id得到用户对象
    static function get_user_obj($user_id)
    {
        $model = new Model();
        //return $model->table("user")->where("id=".$user_id)->find();
        $user_obj = $model->query("select zyk_user.*,zyk_customer.* from zyk_user,zyk_customer where zyk_user.id=zyk_customer.user_id and zyk_user.id=" . $user_id);
        return $user_obj[0];
    }

    //根据用户id得到用户对象
    static function get_user_obj_by_name($name)
    {
        $model = new Model();
        //return $model->table("user")->where("id=".$user_id)->find();
        $user_obj = $model->query("select zyk_user.*,zyk_customer.* from zyk_user,zyk_customer where zyk_user.id=zyk_customer.user_id and zyk_user.name='$name'");
        return $user_obj[0];
    }

    //根据用户id得到推荐人对象
    static function get_tjr_obj($user_id)
    {
        $model = new Model();
        $user_obj = self::get_user_obj($user_id);
        return self::get_user_obj($user_obj['tjr_id']);
    }

    /**
     * 注册添加子孙链
     * Enter description here ...
     * $tjr_id 推荐人id
     */
    static function addChildLink($user_id, $tjr_id)
    {
        //获取推荐人对象
        $tjrUserObj = self::get_user_obj($tjr_id);

        $son = $tjrUserObj['son'];
        if (empty($son)) {
            $son = $user_id;
        } else {
            $son .= ",$user_id";
        }

        $data['son'] = $son;
        $model = new Model();
        $model->table("user")->where("id=" . $tjr_id)->data($data)->update();
        if (!empty($tjrUserObj['tjr_id'])) {
            self::addChildLink($user_id, $tjrUserObj['tjr_id']);
        }
    }

    /**
     * 创建编码
     */
    static function create_number($uname)
    {
        $uname = strval(trim($uname));
        $model = new Model();
        $demo_number = substr($uname, -6);
        $res = $model->query("select * from zyk_user where number='{$demo_number}';");
        if (!empty($res)) {
            return substr($uname, -7);
        }
        return $demo_number;
        /*
        $str = md5(microtime());
        $number = substr(md5($id.$str),0,6);
        */
//         $model = new Model();

//         $result = $model->table("user")->where("number='{$number}'")->find();
//         if(!empty($result))
//         {
//             return self::create_number($id);
//         }

        //return $number;
    }


    /**  检查sql语句是否成功
     * @param $sql
     * @return bool
     */
    static function check_is_exists_of_talbe($sql)
    {
        $model = new Model();
        $result = $model->query($sql);
        if (empty($result)) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 得到客户端ip地址(ipv4地址)
     * Enter description here ...
     */
    static function get_real_ip()
    {
        if (isset($_ENV["HOSTNAME"]))
            $MachineName = $_ENV["HOSTNAME"];
        else if (isset($_ENV["COMPUTERNAME"]))
            $MachineName = $_ENV["COMPUTERNAME"];
        else $MachineName = "";
        return gethostbyname($MachineName);

    }

    /**
     * 判断订单是否已评价
     * Enter description here ...
     * @param unknown_type $order_no
     */
    static function check_order_is_comment($order_no)
    {
        $model = new Model();
        $review_obj = $model->table("review")->where("order_no='{$order_no}'")->find();
        if (!empty($review_obj['content']) && !empty($review_obj['comment_time'])) {
            return true;
        }
        return false;
    }

    static function huanyuan_order_refund_info($order_id)
    {
        $model = new Model();
        $order_obj = $model->table("order")->where("id=$order_id")->find();
        $order_amount = $order_obj['order_amount'];
        $payment_id = intval($order_obj['payment']);
        $user_id = $order_obj['user_id'];

        $payment_obj = Common::get_payment_obj_by_id($payment_id);

        $demo_account_type = $payment_obj['pay_zd'];
        $model->table("customer")->data(array($demo_account_type => "`$demo_account_type`+$order_amount"))->where("user_id=$user_id")->update();

        /*
        if( $payment_id ===1)//账户余额支付
        {
            $model->table("customer")->data( array('balance'=>"`balance`+$order_amount") )->where("user_id=$user_id")->update();
        }
        elseif($payment_id == 10)//积分
        {
            $model->table("customer")->data( array('ok_xfjf'=>"`ok_xfjf`+$order_amount") )->where("user_id=$user_id")->update();
        }
        elseif($payment_id == 11)//消费券
        {
            $model->table("customer")->data( array('voucher'=>"`voucher`+$order_amount") )->where("user_id=$user_id")->update();
        }
        else
        {

        }
        */

    }

    /**
     * 得到注册二维码图片
     * Enter description here ...
     * @param unknown_type $user_id
     */
    static function get_reg_erwei_img($user_id)
    {
        $model = new Model();

        $config = Config::getInstance();
        $domain = $config->get("domain");

        $tjr_obj = self::getUserInfoByUId($user_id);
        $tjr_name = $tjr_obj['name'];

        if (empty($tjr_obj)) {
            $url = $domain . "/index.php?con=mobile&act=register";
        } else {
            $url = $domain . "/index.php?con=wymobile&act=reg&tjr_name=$tjr_name";
        }

        include_once 'phpqrcode/phpqrcode.php';

        $errorCorrectionLevel = 'L';//容错级别

        $matrixPointSize = 5;//生成图片大小

        //生成二维码图片

        QRcode::png($url, "./data/erwei_img/erwei" . $user_id . ".png", $errorCorrectionLevel, $matrixPointSize, 2);

        $logo = './data/logo.png';//准备好的logo图片

        $QR = "./data/erwei_img/erwei" . $user_id . ".png";//已经生成的原始二维码图


        if ($logo !== FALSE) {

            $QR = imagecreatefromstring(file_get_contents($QR));

            $logo = imagecreatefromstring(file_get_contents($logo));

            $QR_width = imagesx($QR);//二维码图片宽度

            $QR_height = imagesy($QR);//二维码图片高度

            $logo_width = imagesx($logo);//logo图片宽度

            $logo_height = imagesy($logo);//logo图片高度

            $logo_qr_width = $QR_width / 7;//logo图像的宽度占整个图片的1/7

            $scale = $logo_width / $logo_qr_width;

            $logo_qr_height = $logo_height / $scale;

            $from_width = ($QR_width - $logo_qr_width) / 2;

            //重新组合图片并调整大小

            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,

                $logo_qr_height, $logo_width, $logo_height);

        }

        //输出图片

        imagepng($QR, "./data/erwei_img/erwei" . $user_id . "_logo.png");

        echo '<img width="180px" height="180px" src="./data/erwei_img/erwei' . $user_id . '_logo.png">';
    }


    /**
     * 得到下载app的二维码图片
     * Enter description here ...
     * @param $user_id
     */
    static function get_download_erwei_img()
    {
        $model = new Model();

        $m = new Model("version");

        $obj = $model->query("select max(version_code) as max_version_code from zyk_version");

        $result = $m->where("version_code=" . $obj[0]['max_version_code'])->find();

        $config = Config::getInstance();

        $domain = $config->get("domain");

        $url = $domain . $result['url'];

        include_once 'phpqrcode/phpqrcode.php';


        $errorCorrectionLevel = 'L';//容错级别

        $matrixPointSize = 5;//生成图片大小

        //生成二维码图片

        QRcode::png($url, "./data/erwei_img/download.png", $errorCorrectionLevel, $matrixPointSize, 2);

        $logo = './data/logo.png';//准备好的logo图片

        $QR = "./data/erwei_img/download.png";//已经生成的原始二维码图


        if ($logo !== FALSE) {

            $QR = imagecreatefromstring(file_get_contents($QR));

            $logo = imagecreatefromstring(file_get_contents($logo));

            $QR_width = imagesx($QR);//二维码图片宽度

            $QR_height = imagesy($QR);//二维码图片高度

            $logo_width = imagesx($logo);//logo图片宽度

            $logo_height = imagesy($logo);//logo图片高度

            $logo_qr_width = $QR_width / 7;//logo图像的宽度占整个图片的1/7

            $scale = $logo_width / $logo_qr_width;

            $logo_qr_height = $logo_height / $scale;

            $from_width = ($QR_width - $logo_qr_width) / 2;

            //重新组合图片并调整大小

            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,

                $logo_qr_height, $logo_width, $logo_height);

        }

        //输出图片

        imagepng($QR, "./data/erwei_img/download_logo.png");

        echo '<img width="180px" height="180px" src="./data/erwei_img/download_logo.png">';
    }


    public static function getCustomerObj($user_id)
    {
        $model = new Model();
        return $model->table("customer")->where("user_id=$user_id")->find();
    }


    /**
     * 根据第3级类别id获得商品
     * Enter description here ...
     * @param unknown_type $cid
     */
    public static function getGoodsListByThirdLevelCategoryId($cid)
    {
        $model = new Model();
        $goods_list = $model->table("goods")->where("category_id=$cid")->select();
        return $goods_list;
    }


    /**
     * 得到一级商品分类
     * Enter description here ...
     */
    public static function getFirstLevelGoodsCategory()
    {
        $model = new Model();
        $category_list = $model->table("goods_category")->where("parent_id=0")->select();
        return $category_list;
    }


    /**
     * 根据类别id获得类别名称
     * Enter description here ...
     * @param unknown_type $cid
     */
    public static function getCategoryNameByCid($cid)
    {
        $model = new Model();
        $category_obj = $model->table("goods_category")->where("id=$cid")->find();
        return $category_obj['name'];
    }


    /**
     * 根据商品类别id获取相应的商品列表 cid为一级分类的id
     * Enter description here ...
     */
    public static function getGoodsListByClassifyId($cid)
    {
        $model = new Model();

        $category_list = $model->table("goods_category")->fields("id")->where("path like '%,{$cid},%'")->select();

        $demo = array();
        for ($i = 0, $c = count($category_list); $i < $c; $i++) {
            $goods_list = $model->table("goods")->fields("id,name,img,sell_price,market_price")->where("is_online=0 and category_id=" . $category_list[$i]['id'])->select();
            for ($j = 0, $cc = count($goods_list); $j < $cc; $j++) {
                $demo[] = $goods_list[$j];
                /*
                if($j<=7)
                {
                    $demo[] = $goods_list[$j];
                }
                */

            }
        }

        return $demo;
    }

    /**
     * 根据订单id得到订单所属的商品列表
     * Enter description here ...
     * @param unknown_type $order_id
     */
    public static function getGoodsListByOId($order_id)
    {
        $model = new Model();
        $order_goods_list = $model->table("order_goods")->where("order_id=$order_id")->select();
        $demo = array();
        for ($i = 0, $c = count($order_goods_list); $i < $c; $i++) {
            $goods_id = $order_goods_list[$i]['goods_id'];
            $goods_obj = Common::getGoodsInfo($goods_id);
            $data['sell_price'] = $order_goods_list[$i]['goods_price'];
            $data['goods_nums'] = $order_goods_list[$i]['goods_nums'];
            $data['img'] = $goods_obj['img'];
            $data['name'] = $goods_obj['name'];
            $data['spec'] = self::getSpecByProductId($order_goods_list[$i]['product_id']);
            $data['goods_id'] = $goods_id;
            $demo[] = $data;
        }
        return $demo;

    }

    /**
     * 根据支付类型获取支付名称
     * Enter description here ...
     * @param unknown_type $payment_id
     */
    public static function getPaymentnameByPId($payment_id)
    {
        $model = new Model();
        $payment_obj = $model->table("payment")->where("id=$payment_id")->find();
        return $payment_obj['pay_name'];
    }

    /**
     * 根据订单号获取订单文本状态
     * Enter description here ...
     * @param unknown_type $order_no
     */
    public static function getOrderTextStatusByNo($order_no)
    {
        $model = new Model();
        $order_status = self::getOrderStateByONo($order_no);
        if ($order_status == 1) {
            return '待付款';
        } elseif ($order_status == 2) {
            return '待发货';
        } elseif ($order_status == 3) {
            return '待收货';
        } elseif ($order_status == 4) {
            return '已完成，待评价';
        } elseif ($order_status == 5) {
            return '退款中';
        } elseif ($order_status == 6) {
            return '退货中';
        } elseif ($order_status == 0) {
            return '已关闭';
        }
    }

    /**
     * 根据订单状态获取订单数量
     * Enter description here ...
     * @param unknown_type $user_id
     * @param unknown_type $status
     */
    public static function getOrderNumByStatus($user_id, $status)
    {
        $model = new Model();
        $order_list = $model->table("order")->fields("order_no")->where("user_id=$user_id")->select();
        $num = 0;
        for ($i = 0, $c = count($order_list); $i < $c; $i++) {
            $order_no = $order_list[$i]['order_no'];
            $order_status = intval(self::getOrderStateByONo($order_no));
            if ($status == 1)//待付款订单的数量
            {
                if ($order_status === 1) {
                    $num++;
                }
            } elseif ($status == 2)//待发货
            {
                if ($order_status === 2) {
                    $num++;
                }
            } elseif ($status == 3)//待收货
            {
                if ($order_status === 3) {
                    $num++;
                }
            } elseif ($status == 4)//待评价
            {
                if ($order_status === 4) {
                    $review_obj = $model->table("review")->where("order_no='{$order_no}'")->find();
                    if (!empty($review_obj['content']) && !empty($review_obj['coment_time'])) {
                        $num++;
                    }

                }
            } elseif ($status == 5)//退换状态
            {
                if ($order_status === 5 || $order_status === 6) {
                    $num++;
                }
            }
        }
        return $num;

    }

    /**
     * 根据product_id得到货品对象
     * Enter description here ...
     */
    public static function getProductObjByPId($product_id)
    {
        $model = new Model();
        $result = $model->table("products")->where("id=$product_id")->find();
        $goods_id = $result['goods_id'];
        $goods_obj = self::getGoodsInfo($goods_id);
        $result['img'] = $goods_obj['img'];
        $result['imgs'] = $goods_obj['imgs'];
        $result['name'] = $goods_obj['name'];
        return $result;
    }

    /**
     * 根据地址id得到一条地址信息
     * Enter description here ...
     * @param unknown_type $addr_id
     */
    public static function getUserAddrObj($addr_id)
    {
        $model = new Model();
        return $model->table("address")->where("id=$addr_id")->find();
    }

    /**
     * 得到用户默认地址,没有话就返回第一条数据
     * Enter description here ...
     * @param unknown_type $user_id
     */
    public static function getUserDefaultAddr($user_id)
    {
        $model = new Model();
        $addr_obj = $model->table("address")->where("user_id=$user_id and is_default=1")->find();
        if (empty($addr_obj)) {
            $addr_list = $model->table("address")->where("user_id=$user_id")->order("id asc")->limit("1")->select();
            return $addr_list[0];
        } else {
            return $addr_obj;
        }

    }


    /**
     * 根据货品号得到规格
     *
     * @param unknown_type $product_id
     */
    public static function getSpecByProductId($product_id)
    {
        $model = new Model();
        $product_obj = $model->table("products")->where("id=$product_id")->find();

        /*
        $arr = explode(";", $product_obj['specs_key']);
        $arr1 = explode(":",$arr[1]);
        $arr2 = explode(":", $arr[2]);
        */

        $spec = unserialize($product_obj['spec']);

        $str = '';
        foreach ($spec as $key => $value) {
            //$str += $value['value'][1];
            $item = $value['value'];
            $str .= " | " . $item[1];
        }
        return mb_substr($str, 2, strlen($str), 'utf-8');

    }


    public static function getGoodsAttrByGIdAndKey($goods_id, $attr)
    {
        $model = new Model();
        $product_list = $model->table("products")->where("goods_id=$goods_id")->select();

        for ($i = 0, $c = count($product_list); $i < $c; $i++) {
            $specs_key = $product_list[$i]['specs_key'];

            $arr = explode(";", $specs_key);
            $arr = array_filter($arr);
            sort($arr);
            $str2 = implode("-", $arr);//2:10-4:26

            $specAttrValueList[$str2] = $product_list[$i];
        }
        return $specAttrValueList[$attr];
    }


    static function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
    {
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
            die('possible deep recursion attack');
        }
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                self::arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }

            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
        $recursive_counter--;
    }

    /**
     *
     * 将数组转化为json字符串
     * @param array $array
     */
    public static function _toJSON($arr)
    {
        self::arrayRecursive($arr, 'urlencode', true);
        $json = json_encode($arr);
        return urldecode($json);
    }


    /**
     * 获得推荐人和节点人用户列表
     * Enter description here ...
     */
    public static function getTjrJdrUserList()
    {
        $model = new Model();
        return $model->table("user")->where("tjr_index=1")->select();
    }
    /************************************************************************************************/

    //得到配置文件值
    public static function getConfigValue($key)
    {
        $config = Config::getInstance();
        return $config->get($key);
    }

    public static function getConfigJjsetValue($key)
    {
        $config = Config::getInstance();
        return $config->get("jjset")[$key];
    }

    public static function getC($id)
    {
        $user_model = new Model("customer");
        return $user_model->where("user_id=" . $id)->find();
    }

    public static function getUid($id)//以用户ID取值
    {
        $user_model = new Model("user");
        return $user_model->where("id=" . $id)->find();
    }

    public static function getUname($uname)//以账号取值
    {
        $user_model = new Model("user");
        return $user_model->where("name='$uname'")->find();
    }

    public static function getDp($id)//以用户id取店铺信息
    {
        $user_model = new Model("dp");
        return $user_model->where("user_id=" . $id)->find();
    }

    public static function getAgent($id)//以用户id取代理信息
    {
        $user_model = new Model("agent");
        return $user_model->where("user_id=" . $id)->find();
    }

    public static function getGoodsInfo($id)//以商品ID取商品信息
    {
        $user_model = new Model("goods");
        return $user_model->where("id=" . $id)->find();
    }

    //根据商品id获得商家信息
    static function getDpInfo($id, $fields)
    {
        $model = new Model('dp as dp');
        $dpinfo = $model->fields("g.u_dp_id,g.id,dp.*")->join("left join goods as g on g.u_dp_id = dp.user_id")->where("g.id=" . $id)->find();
        if (!empty($dpinfo)) {
            return $dpinfo[$fields];
        } else {
            return 0;
        }
    }

    public static function getShenfenName($shenfen_id)
    {
        //$shenfen_arr = array(0=>'普通',1=>'创客',2=>'商家',3=>'社区店',4=>'股东');
        $shenfen_arr = array(0 => '普通', 1 => '服务中心', 2 => '分公司');
        return $shenfen_arr[$shenfen_id];
    }

    public static function getAgentName($id)
    {
        $agent_arr = array(1 => '省代', 2 => '市代', 3 => '县代');
        return $agent_arr[$id];
    }

    //资助状态
    public static function getZzt($id)
    {
        $agent_arr = array(0 => '<span class="text-warning">审核中</span>', 1 => '<span class="text-info">待资助</span>', 2 => '<span class="green">已资助</span>', 3 => '<span class="text-success">已还款</span>');
        return $agent_arr[$id];
    }

    public static function getBzName($bizhong)
    {
        $bz_arr = array('balance' => '现金币', 'jkb' => '借款币', 'gwb' => '购物币', 'xxb' => '学习币', 'xyb' => '信用币');
        return $bz_arr[$bizhong];
    }

    //验证二级密码
    public static function getPass2($uid, $pass)
    {
        $p = self::getUid($uid)['passwordtwo'];
        if ($p != CHash::md5($pass)) {
            $is_ok = 0;
        } else {
            $is_ok = 1;
        }
        return $is_ok;
    }

    //取得当前时间
    public static function getDate($dort)
    {
        //d短日期，t长日期
        switch ($dort) {
            case 'd':
                $time = date('Y-m-d');
                break;
            case 't':
                $time = date('Y-m-d H:i:s');
                break;
        }
        return $time;

    }

    //提示错误信息
    // public static function alertMsg(){
    //     echo "<script>parent.close_dialog();</script>";
    // }

    //根据商品id获得商品的销量
    static function getGoodNumByGId($id)
    {
        $sell_nums = 0;
        $model = new Model('order as o');
        $where = "o.delivery_status>0 and o.status>2 and o.pay_status=1 and og.goods_id=$id";
        $sell_nums = $model->fields("o.*,og.*,sum(og.goods_nums) as nums")->join("left join order_goods as og on o.id = og.order_id")->where($where)->find();
        return $sell_nums['nums'];
    }


    //检测表达式
    private static function check_condition($condition)
    {
        return !!preg_match('/^(\S+--\S+--\S+--[\S ]+__)*(\S+--\S+--\S+--[\S ]+)$/', $condition);
    }

    //字符串转条件
    public static function str2where($condition)
    {
        if (self::check_condition($condition)) {
            $condition = preg_replace('/^(and|or)/i', '', $condition);
            $condition = str_replace(array('--', '__'), array(' ', "' "), $condition);
            $old_char = array(' ne ', ' eq ', ' lt ', ' gt ', ' le ', ' ge ', ' ct ', ' nct ');
            $new_char = array(" != '", " = '", " < '", " > '", " <= '", " >= '", " like '%", " not like '%");
            $condition = str_replace($old_char, $new_char, $condition);
            $condition = preg_replace("/\s+(like\s+'[^']+)('|$)/i", " $1%$2", $condition);
            if ($condition != '') $condition .= "'";
            return $condition;
        }
        return null;
    }

    //生成订单编号
    public static function createOrderNo()
    {
        return date('YmdHis') . rand(100000, 999999);
    }

    //发放代金券
    public static function paymentVoucher($voucherTemplate, $userID = null)
    {
        $model = new Model("voucher");
        do {
            $account = strtoupper(CHash::random(10, 'char'));
            $password = strtoupper(CHash::random(10, 'char'));
            $obj = $model->where("account = '$account'")->find();
        } while ($obj);
        $start_time = date('Y-m-d H:i:s');
        $end_time = date('Y-m-d H:i:s', strtotime('+' . $voucherTemplate['valid_days'] . ' days'));
        $model->data(array('account' => $account, 'password' => $password, 'name' => $voucherTemplate['name'], 'value' => $voucherTemplate['value'], 'start_time' => $start_time, 'end_time' => $end_time, 'money' => $voucherTemplate['money'], 'is_send' => 1, 'user_id' => $userID))->insert();
    }

    //分类的树状化数组
    public static function treeArray($datas)
    {
        $result = array();
        $I = array();
        foreach ($datas as $val) {
            $sort = intval($val['sort']);
            if ($val['parent_id'] == 0) {
                if (isset($result[$val['sort']])) $i = count($result[$val['sort']]);
                else $i = 0;
                $result[$sort][$i] = $val;
                $I[$val['id']] = &$result[$sort][$i];
                krsort($result);
            } else {
                if (isset($I[$val['parent_id']]['child'][$sort])) $i = count($I[$val['parent_id']]['child'][$sort]);
                else $i = 0;
                $I[$val['parent_id']]['child'][$sort][$i] = $val;
                krsort($I[$val['parent_id']]['child']);
                $I[$val['id']] = &$I[$val['parent_id']]['child'][$sort][$i];
            }
        }
        return self::parseTree($result);
    }

    //递归树状数组
    public static function parseTree($result, &$tree = array())
    {
        foreach ($result as $items) {
            if (is_array($items)) {
                foreach ($items as $item) {
                    $tem = $item;
                    if (isset($item['child'])) unset($tem['child']);
                    $tree[] = $tem;
                    if (isset($item['child'])) self::parseTree($item['child'], $tree);
                }
            }
        }
        return $tree;
    }

    //价格区间计算
    static function priceRange($range)
    {
        $d0 = intval($range['min'], -2);
        $d1 = intval(($range['min'] + $range['avg']) / 2);
        $d2 = intval($range['avg']);
        $d3 = intval(($range['max'] + $range['avg']) / 2);
        $d4 = intval($range['max']);

        if ($d4 > $d3 && $d3 > $d2 && $d2 > $d1 && $d1 > $d0) {
            $d1 = self::formatInt($d1);
            $d2 = self::formatInt($d2);
            $d3 = self::formatInt($d3);
            $d4 = self::formatInt($d4);
            $price_range[0] = '0-' . $d1;
            if ($d2 - $d1 > 2) $price_range[1] = $d1 . '-' . ($d2 - 1);
            else $price_range[1] = $d1 . '-' . $d2;
            if ($d3 - $d2 > 2) $price_range[2] = $d2 . '-' . ($d3 - 1);
            else $price_range[2] = $d2 . '-' . $d3;
            if ($d4 - $d3 > 2) $price_range[3] = $d3 . '-' . ($d4 - 1);
            else $price_range[3] = $d3 . '-' . $d4;
            $price_range[4] = "$d4";
            return $price_range;
        } else {
            if ($d2 != 0) {
                $d2 = self::formatInt($d2);
                if ($d2 > 1) return array(0 => ('0-' . ($d2 - 1)), 1 => "$d2");
                else return array(0 => ('0-' . ($d2)), 1 => "$d2");
            } else if ($range['min'] != 0) {
                return array(0 => ('0-' . ($range['min'])), 1 => "$range[min]");
            } else return array();
        }
    }

    static function formatInt($value)
    {
        $len = strlen($value);
        switch ($len) {
            case 1:
                break;
            case 2:
                $value = round($value, -1);
                break;
            case 3:
            case 4:
                $value = round($value, -2);
                break;
            default:
                $value = round($value, 2 - $len);
                break;
        }
        return $value;
    }

    //thumb
    static function thumb($image_url, $w = 200, $h = 200)
    {
        if (preg_match('@http://@i', $image_url)) return $image_url;
        $access_image_size = array(
            '220_220' => true,
            '100_100' => true,
            '367_367' => true
        );
        $theme_config = Tiny::app()->getTheme()->getConfigInfo();
        if ($theme_config != null && isset($theme_config['access_image_size'])) {
            $access_image_size = array_merge($access_image_size, $theme_config['access_image_size']);
        }
        if (func_num_args() == 2) $h = $w;
        if ($image_url == '') return '';

        if (isset($access_image_size[$w . '_' . $h])) {

            $ext = strtolower(strrchr($image_url, '.'));
            $result_url = $image_url . '__' . $w . '_' . $h . $ext;
            if (!file_exists(APP_ROOT . $result_url)) {
                $image = new Image();
                $image->suffix = 'f_w_h';
                $result_url = $image->thumb(APP_ROOT . $image_url, $w, $h);
                $result_url = str_replace(APP_ROOT, '', $result_url);
            }
            return Url::urlFormat('@' . $result_url);
        } else {
            return Url::urlFormat('@' . $image_url);
        }

    }

    //自动登录时的用户信息
    static function autoLoginUserInfo()
    {
        $cookie = new Cookie();
        $cookie->setSafeCode(Tiny::app()->getSafeCode());
        $autologin = $cookie->get('autologin');
        $obj = null;
        if ($autologin != null) {
            $account = Filter::sql($autologin['account']);
            $password = $autologin['password'];
            $model = new Model("user as us");
            $obj = $model->join("left join customer as cu on us.id = cu.user_id")->fields("us.*,cu.group_id,cu.user_id,cu.login_time,cu.mobile")->where("us.email='$account' or us.name='$account' or cu.mobile='$account'")->find();
            if ($obj['password'] != $password) {
                $obj = null;
            }
        }
        return $obj;
    }

    //取得支付方式信息
    static function getPaymentInfo($id)
    {
        $model = new Model('payment as pa');
        $payment = $model->join('left join pay_plugin as pp on pa.plugin_id = pp.id')->where("pa.id = " . $id)->find();
        return $payment;
    }


    /**
     * 根据地址id获取一条完整的地址信息
     * @param unknown_type $id
     */

    static function getAreaObjById($id)
    {
        $model = new Model("address");
        $obj = $model->where("id=" . $id)->find();
        return $obj;
    }

    static function getUserInfoByUId($id)

    {

        $user_model = new Model("user");

        return $user_model->where("id=" . $id)->find();

    }

    /**
     * 根据订单号得到一条订单信息
     *
     * @param unknown_type $orderId
     */

    static function getOrderInfoByONo($orderNo)

    {

        $model = new Model("order");

        return $model->where("order_no='{$orderNo}'")->find();

    }


    /**
     * 根据订单号得到订单中的商品信息
     * return 数组
     */
    static function getGoodsInfoByONo($orderNo)
    {
        if (empty($orderNo)) return false;
        $order_goods_model = new Model("order_goods");
        $goods_model = new Model("goods");

        //根据订单号得到一条订单详细信息(主要是为了得到订单id)
        $obj = self::getOrderInfoByONo($orderNo);

        //根据订单id得到商品id数组
        $gid_arr = $order_goods_model->fields("goods_id")->where("order_id=" . $obj['id'])->select();

        $arr = array();
        for ($i = 0; $i < count($gid_arr); $i++) {
            //在订单商品列表中根据商品id循环获得商品信息
            $arr[$i] = $goods_model->where("id=" . $gid_arr[$i]['goods_id'])->find();//查询结果可扩展
        }
        if (empty($arr)) return false;
        return $arr;
    }


    /**
     * 根据订单号获得订单的状态
     * Enter description here ...
     */

    static function getOrderStateByONo($orderNo)

    {

        $sta = 0;

        $obj = Common::getOrderInfoByONo($orderNo);


        $status = intval($obj['status']);

        $pay_status = intval($obj['pay_status']);


        $delivery_status = intval($obj['delivery_status']);

        if (($status === 2 || $status === 3) && $pay_status === 0 && $delivery_status === 0) {

            //待付款

            $sta = 1;

        } elseif (($status === 2 || $status === 3) && $pay_status === 1 && $delivery_status === 0) {

            //待发货

            $sta = 2;

        } elseif ($status === 3 && $pay_status === 1 && $delivery_status === 1) {

            //待收货

            $sta = 3;

        } elseif (($status === 2 || $status === 3) && ($pay_status === 2 || $pay_status === 3) && $delivery_status === 0) {

            //退款状态

            $sta = 5;

        } elseif (($status === 3 || $status === 4) && ($pay_status === 2 || $pay_status === 3) && ($delivery_status === 1 || $delivery_status === 2)) {

            //退货状态

            $sta = 6;

        } elseif ($status === 4 && $pay_status === 1 && $delivery_status === 2) {

            $sta = 4;//完成状态（在它下进行判断是否能评论）

//			$review_model=new Model("review");

//			$result=$review_model->where("order_no='{$obj['order_no']}'")->find();

//			if(empty($result))

//			{

//				//待评价

//				$sta=6;

//			}

//			else

//			{

//				//已评价

//				$sta=7;

//			}

        } elseif ($status === 5) {

            //关闭的订单

            $sta = 0;

        }

        return $sta;

    }

    /** 判断区域是否被占领
     * @param $agent 代理级别
     * @param $dl_area 代理区域
     * @return bool  true 被占领  false 没被占领
     */
    static function check_area_exist($agent,$dl_area)
    {
        $model = new Model();

        if ($agent == 3) { //判断县级是否存在
            $dl_area3 = $dl_area;
            $exit = $model->table("user as us")->join("inner join customer as cu on us.id = cu.user_id")->fields("us.*,cu.*")->where("status=1 and group_id=3 and dl_area='$dl_area3'")->find();
            if ($exit) {
                return true;
            }
        }

        if ($agent == 4) { //判断市级是否存在
            $post_area = explode(',',$dl_area);
            $province = $post_area[0];
            $city = $post_area[1];
            $obj_agent4 = $model->table("user as us")->join("inner join customer as cu on us.id = cu.user_id")->fields("us.*,cu.*")->where("status=1 and group_id=4")->findAll();
            for ($i=0;$i<count($obj_agent4);$i++) {
                $dl_area = $obj_agent4[$i]['dl_area'];
                $arr = explode(',',$dl_area);
                if ($arr[0] == $province && $arr[1] == $city) {
                    return true;
                }
            }
        }
        return false;
    }

    /** 根据dl_area获得代理地址
     * @param $area 字段dl_area
     * @return string 代理地址
     */
    static function area_name($area)
    {
        if (empty($area)) {
            return '无';
        }
        $areas = explode(',', $area);
        $model = new Model();
        $position = '';
        for ($i = 0; $i < count($areas); $i++) {
            $area = $model->table('area')->where('id=' . $areas[$i])->find();
            $position .= $area['name'] . ' ';
        }
        return $position;
    }

    /** 根据投资级别获得资产
     * @param $result 返回资产
     * @return mixed
     */
    static function get_zc_limit($result)
    {
        if ($result['id'] == 1) {
            $zc = $result['money'] * self::getConfig('jjset_grade_times1');
        } else if ($result['id'] == 2) {
            $zc = $result['money'] * self::getConfig('jjset_grade_times2');
        } else if ($result['id'] == 3) {
            $zc = $result['money'] * self::getConfig('jjset_grade_times3');
        } else if ($result['id'] == 4) {
            $zc = $result['money'] * self::getConfig('jjset_grade_times4');
        }
        return $zc;
    }

    /** 根据id获得用户对象
     * @param $tjr_id
     * @return mixed
     */
    static function get_tjr_name($tjr_id)
    {
        $model = new Model();
        $obj = $model->table('user')->where('id='.$tjr_id)->find();
        return $obj;
    }

    /**  根据用户id查询投资对象
     * @param $id
     */
    static function get_grade ($id)
    {
        $model= new Model();
        $customer_obj = $model->table('customer')->where('user_id='.$id)->find();
        $grade = $model->table('grade')->where('id='.$customer_obj['group_id'])->find();
        return $grade;
    }

    /** 通过代理级别获得相应奖金
     * @param $group_id
     */
    static function get_lx_money ($group_id)
    {
        $model = new Model();
        $grade = $model->table('grade')->where('id='.$group_id)->find();
        return $grade['money'];
    }

    static function get_dp_by_user($user_id)
    {
        $model = new Model();

        $dp_info = $model ->table("dp")->where("user_id =".$user_id)->find();
        return $dp_info;
    }

    /**
     * 判断是否存在县级
     * true 存在  false 不存在
     */
    static function judge_area_county ($user_obj)
    {
        $area = $user_obj['dl_area'];
        if (empty($area)) {
            return false;
        }
        $arr = explode(',',$area);
        $number = count($arr);
        if ($number == 3) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 判断是否存在市级
     * true 存在  false 不存在
     */
    static function judge_area_city ($user_obj)
    {
        $area = $user_obj['dl_area'];
        if (empty($area)) {
            return false;
        }
        $arr = explode(',',$area);
        $number = count($arr);
        if ($number == 2) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 通过代理区域获得代理区域名称
     */
    static function get_dl_area_name ($dl_area)
    {
        if (empty($dl_area)) {
            return '无';
        } else {
            $arr = explode(',',$dl_area);
            $province = $arr[0];
            $city = $arr[1];
            $county = $arr[2];
            $model = new Model();
            $province_name = $model->table('area')->where('id='.$province)->find()['name'];
            $city_name = $model->table('area')->where('id='.$city)->find()['name'];
            $county_name = $model->table('area')->where('id='.$county)->find()['name'];
            return $province_name." ".$city_name." ".$county_name;
        }
    }

    /**  通过投资id获得投资级别
     * @param $group_id
     */
    static function get_agent_name ($group_id)
    {
        if ($group_id == 1) {
            return '一级代理';
        } else if ($group_id == 2) {
            return '二级代理';
        } else if ($group_id == 3) {
            return '县代理';
        } else if ($group_id == 4) {
            return '市代理';
        }
    }


    /**
     *
     */
    static function get_son_user ($childs,$childs_id,$model,$i=1)
    {

        $childs_two = [];
        foreach ($childs as $child) {
                $childs_id[] = $child;
                $chil = $model->query("select id from zyk_user where tjr_id=".$child);//子二代单个对象
                foreach ($chil as $chi) {
                    $childs_two[] = $chi['id'];
                }
        }
//        print_r($childs_two);die;
//
        $i++;
        if ($i<20) {
             return self::get_son_user($childs_two,$childs_id,$model,$i);
        }
        return $childs_id;
    }

    /**
     * @return array 根据一个id 获取其下的所有用户[包括自己]
     */
    static function get_sons_tjrs($id,$dai)
    {
        $model = new Model();

        $users = $model->query("select * from zyk_user where id = $id");

        $allArray = [];
        $i =0;
        while($i< $dai)
        {
            $array= [];
            foreach ($users as $user) {
                $allArray[] = $user['id'];
                $array[] = $user['id'];

            }
            $str1 = implode(",", $array);

            $users = $model->query("select * from zyk_user where tjr_id in($str1)"); //第一代
            $i++;

        }

        return $allArray;

    }

    /**
     * @获取某个id下的所有分类
     * @return mixed
     */
    public function all_cates()
    {

        $father_cate = [];
        $array_cate =  $this->getAll(63,$father_cate);
        if($array_cate){
            $array = ['result' => 0, 'msg' => '获取成功！', 'all_cate' => $array_cate];
        }else{
            $array = ['result' => 1, 'msg' => '获取失败！'];
        }
//        var_dump($array);
        echo json_encode($array);
    }

    /**
     * @param $id
     * @param $father_cate  //获取其下面的所有分类
     * @return mixed
     */
    public function getAll($id, $father_cate)
    {
        $model = new Model();
        $fathers = $model ->table('goods_category')->where("parent_id= $id")->order("sort desc")->findAll();
        $cate = array();
        foreach($fathers as $father){

            $cate['title'] =$father['name'];
            $cate['thumb'] = Url::getHost() . '/'.$father['img'];
            $cate['id'] =$father['id'];
            $cate['pid'] =$father['parent_id'];
            $cate['sort'] =$father['sort'];

            $sons = $model ->table('goods_category')->where("parent_id= {$father['id']}")->order("sort desc")->findAll();
            if(!empty($sons))
            {
                $cate['childs']=$this->getAll($father['id'],$father_cate);
            }else{

                $cate['childs']="";
            }
            array_push($father_cate,$cate);

        }

        return $father_cate;
    }


    /**
     * 删除某个顶级分类下所有商品
     */
    public function delGoodsByCate()
    {
        $father_cate = [];
        $array_cate = $this->getAllCateTest(64);

        foreach($array_cate as $cate)
        {
            $father_cate[] = $cate['id'];

            if($cate['childs'])
            {
                foreach($cate['childs'] as  $mm_id)
                {
                    $father_cate[] = $mm_id['id'];
                }

            }
        }


        $model = new Model();
        $model->query("start transaction");
        foreach($father_cate as $nn_id)
        {
            $goods = $model->table("goods")->where("category_id = '{$nn_id}'")->findAll();
            if($goods)
            {
                foreach($goods as $good)
                {
                    $id = $good['id'];
                    $res  =  $model->table("goods")->where("id = $id")->delete();

                    if(!$res)
                    {
                        $model->query("rollback");
                    }
                }

            }

        }
        $model->query("commit");

    }


    public function getAllCateTest($id)
    {
        $model = new Model();
        $childs = $model->table('goods_category')->where("parent_id= $id")->order("sort desc")->findAll();
        $cate = array();
        foreach ($childs as $child) {

            $temp['title'] = $child['name'];

            $temp['id'] = $child['id'];
            $temp['sort'] = $child['sort'];
            $sons = $model->table('goods_category')->where("parent_id= {$child['id']}")->order("sort desc")->findAll();
            if (!empty($sons)) {
                $temp['childs'] = $this->getAllCate($child['id']);
            } else {
                $temp['childs'] = "";
            }
            array_push($cate, $temp);

        }
        return $cate;
    }

    /**
     * @param $time 传过来的时间戳
     * @return bool|string 返回多久之前,
     */
    function showWriteTime($time)
    {
        $interval = time() - $time;
        $format = array(
            '31536000'  => '年',
            '2592000'   => '个月',
            '604800'    => '星期',
            '86400'     => '天',
            '3600'      => '小时',
            '60'        => '分钟',
            '1'         => '秒'
        );
        foreach($format as $key => $value)
        {
            $match = floor($interval / (int) $key );
            if(0 != $match)
            {
                return $match . $value . '前';
            }
        }
        return date('Y-m-d', $time);
    }

}

//获取所有下级 children
   public function hTree_leader_org($arr, $pid = -1)
    {
        foreach ($arr as $k => $v) {
            if ($v['leader_id'] == $pid) {
                $data[$v['id']] = $v;
                if (self::hTree_leader_org($arr, $v['id'])) {
                    $a = self::hTree_leader_org($arr, $v['id']);
                    $data[$v['id']]['children'] = array_values($a);
                }
            }
        }
        return isset($data) ? $data : array();
    }
/**
 * 商品分类列表 根据$parant_id的值获取其下面的所有类型
 */
  function get_list($cates, $parent_id = 0)
{
    $gc_list = array();
    foreach ($cates as $v) {
        if ($v->parent_id == $parent_id) {
            $gc_parent = MGoodsCategory::cateInfo($v);
            $gc_list[] = $gc_parent;
            $gc_list = array_merge($gc_list, self::get_list($cates, $v->id));
        }

    }
    return $gc_list;
}

/**
 *  商品分类列表显示信息
 *  分类对象
 */
  function cateInfo($v)
{
    $count = count(array_filter(explode(',', $v->path)));
    $gc_parent = [
        'id' => $v->id,
        'name' => str_repeat('— ', $count - 1) . $v->name,
        'parent_name' => MGoodsCategory::getCName($v->parent_id),
        'type_name' => MGoodsType::getTName($v->type_id),
        'alias' => $v->alias,
        'nav_show' => $v->nav_show,
        'list_show' => $v->list_show,
        'sort' => $v->sort
    ];

    return $gc_parent;
}
